package logic

import (
	"context"
	"fmt"
	"reflect"
	"go-zero-service/service/user/api/internal/svc"
	"go-zero-service/service/user/api/internal/types"
	"github.com/zeromicro/go-zero/core/logx"
	"encoding/json"
	elastic "github.com/olivere/elastic/v7"
)

type ElasticLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewElasticLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ElasticLogic {
	return &ElasticLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ElasticLogic) Elastic(req *types.ElasticTestReq) (resp []*types.ElasticTestReply, err error) {
	// todo: add your logic here and delete this line
	l.svcCtx.Elastic.Index().Index("testelastuc").Id(req.Name).BodyJson(&req).Do(context.Background())

	resc, err := l.svcCtx.Elastic.Get().Index("testelastuc").Id(req.Name).Do(context.Background())
	if err != nil {
        panic(err)
    }
    if resc.Found {
		te := types.ElasticTestReply{}
		json.Unmarshal(resc.Source, &te)
        fmt.Printf("Got document %s in version %d from index %s\n", resc.Id, resc.Version, resc.Index)
		fmt.Printf("Got document value %s, name %s, age %d, content %s\n", string(resc.Source), te.Name, te.Age, te.Content)
    }

	// term 级别的查询
    termQuery := elastic.NewTermQuery("name", req.Name)
    searchResult, err := l.svcCtx.Elastic.Search().
        Index("testelastuc").
        Query(termQuery).
        //Sort("age", true). // sort by "age" field, ascending
        //From(0).Size(10).   // take documents 0-9
        Pretty(true). // pretty print request and response JSON
        Do(context.Background())       // execute
    if err != nil {
        // Handle error
        panic(err)
    }

    // 将结果，循环打印出来
    var ttyp *types.ElasticTestReply
    for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
        if t, ok := item.(*types.ElasticTestReply); ok {
            fmt.Printf("types.ElasticTestReply by %s: %d, content %s\n", t.Name, t.Age, t.Content)
			node := &types.ElasticTestReply{
				Name: t.Name,
				Age:  t.Age,
				Content: t.Content,
			}

			resp = append(resp, node)
        }
    }

	return resp,err
}
